//-----------------------------------------------------------------------
// <copyright file="cmdImporter.cs" company="Microsoft">
// This should contain the copyright text
// </copyright>
// <summary>This contains the class for the command line interface</summary>
// <author>Kimmo Forss</author>
//-----------------------------------------------------------------------

namespace SharePointImporter.CommandLine
{
    using System;
    using System.IO;
    using SharePoint.ImportExport.Core;
    using SharePoint.ImportExport.Importer;

    /// <summary>
    /// This is the cmd line class for the SharePoint importer
    /// </summary>
    public static class Import
    {
        /// <summary>
        /// This is the main function
        /// </summary>
        /// <param name="args">Comman line arguments</param>
        [STAThread]
        public static void Main(string[] args)
        {
            ImportWrapper importer = new ImportWrapper();
            if (args.Length > 0)
            {
                if (args.Length == 1)
                {
                    if (args[0] == "/?")
                    {
                        PrintUsage();
                        return;
                    }
                }
                else
                {
#if DEBUG
                    Console.WriteLine("Attach debugger");
                    Console.ReadLine();
#endif
                    Parameters parameters = new Parameters();
                    string lastError;
                    if (!parameters.ProcessArgs(args, out lastError))
                    {
                        Console.WriteLine("Incorrect parameters! " + lastError);
                        Console.WriteLine(string.Empty);
                        PrintUsage();
                        return;
                    }

                    Console.WriteLine("*******************************************************");
                    Console.WriteLine("You are perfoming an import with the following options");
                    Console.WriteLine("\t Data file is read from: " + parameters.DirectoryName);
                    if (parameters.ManagedPath.Length > 0)
                    {
                        Console.WriteLine("\t Import is performed to: " + parameters.WebApplicationURL + "/" + parameters.ManagedPath + "/" + parameters.SiteName);
                    }
                    else if (parameters.SiteName.Length > 0)
                    {
                        Console.WriteLine("\t Import is performed to: " + parameters.WebApplicationURL + "/" + parameters.SiteName);
                    }
                    else
                    {
                        Console.WriteLine("\t Import is performed to: " + parameters.WebApplicationURL);
                    }
                    if (parameters.AllowImportToExistingSites)
                    {
                        Console.WriteLine("\t Import to existing sites is allowed");
                    }
                    else
                    {
                        Console.WriteLine("\t Import to existing sites is not allowed");
                    }

                    if (parameters.AllowImportToExistingLibraries)
                    {
                        Console.WriteLine("\t Import to existing document libraries is allowed");
                    }
                    else
                    {
                        Console.WriteLine("\t Import to existing document libraries is not allowed");
                    }

                    Console.WriteLine();

                    Console.WriteLine("*******************************************************");

                    Logger.Init("import" + DateTime.Now.ToString("MMddHHmm") + ".log", parameters.ReportLevel);
                    Logger.LogDataSendingEvent += new Logger.LogDataEventHandler(IncomingEventLogData);

                    if (importer.Init(true))
                    {
                        string contentDeploymentFiles = string.Empty;
                        if (parameters.CheckSchema)
                        {
                            importer.ValidateFiles(parameters.DirectoryName, true);
                        }
                        else
                        {
                            string s = string.Empty;
                            if (File.Exists(parameters.DirectoryName + "\\firstrun.txt"))
                            {
                                s = File.ReadAllText(parameters.DirectoryName + "\\firstrun.txt");
                            }
                            else
                            {
                                parameters.Bypass = false;
                            }

                            if (!parameters.Bypass)
                            {
                                importer.Process(parameters.DirectoryName, parameters.WebApplicationURL, parameters.AllowImportToExistingSites, parameters.AllowImportToExistingLibraries, parameters.SetSecurity, true, parameters.ManagedPath, parameters.SiteName,parameters.Sitedefinition,parameters.Owner,parameters.Contact, out s);
                                File.WriteAllText(parameters.DirectoryName + "\\firstrun.txt", s);
                                Logger.Close();
                                Logger.Init("import" + DateTime.Now.ToString("MMddHHmm") + ".log", parameters.ReportLevel);
                            }

                            ContentDeploymentInfo cdi = new ContentDeploymentInfo();
                            if (cdi.ReadFromString(s))
                            {
                                importer.ImportData(cdi, parameters.DirectoryName, parameters.WebApplicationURL, true, true, "ImportData.log");
                            }
                        }
                    }
#if DEBUG
                    Console.WriteLine("Done");
                    Console.ReadLine();
#endif
                    Logger.Close();
                    Logger.LogDataSendingEvent -= new Logger.LogDataEventHandler(IncomingEventLogData);
                }
            }
            else
            {
                PrintUsage();
                return;
            }
        }

        /// <summary>
        /// Prints the usage information
        /// </summary>
        private static void PrintUsage()
        {
            Console.WriteLine("---");
            Console.WriteLine("Usage:");
            Console.WriteLine("-folder x:\\folder");
            Console.WriteLine("-webApp http://server");
            Console.WriteLine(string.Empty);
            Console.WriteLine("or");
            Console.WriteLine("-folder x:\\folder");
            Console.WriteLine("-ValidateXML");
            Console.WriteLine(string.Empty);
            Console.WriteLine("Optional:");
            Console.WriteLine("-ManagedPath (Sites etc)");
            Console.WriteLine("-SiteUrl \" Site Url of new/existing site\"");
            Console.WriteLine("-CreateListTemplates");
            Console.WriteLine("-OKToImportToExistingSite");
            Console.WriteLine("-OKToImportToExistingLibrary");
            Console.WriteLine("-ImportSecurity");
            Console.WriteLine("-ImportDesign");

            Console.WriteLine("-reportLevel Information|Warning|Error");
            Console.WriteLine(string.Empty);
            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();
        }

        /// <summary>
        /// This is the event receiver
        /// </summary>
        /// <param name="sender">Who raised the event</param>
        /// <param name="e">Event raised</param>
        private static void IncomingEventLogData(object sender, SPEventArgs e)
        {
            string message = e.Message;
            message = message.Replace("Information-", "Information\t");
            message = message.Replace("Warning-", "Warning\t");
            message = message.Replace("Error-", "Error\t\t");
            message = message.Replace("Progress-", "Progress\t");
            string logArgs = DateTime.Now.ToLongTimeString()  + "  " + message;
            Console.WriteLine(logArgs);
        }
    }
}
